/******************************************************************************
 * @File name   :      CardDefineServiceImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Aug 12, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Aug 12, 2015 1:39:56 PM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.card.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.card.constants.CardConstants;
import com.cap.bts.crmdp.dealer.card.dao.ICardExportDao;
import com.cap.bts.crmdp.dealer.card.domain.CardGeneration;
import com.cap.bts.crmdp.dealer.card.dto.CardExportDto;
import com.cap.bts.crmdp.dealer.card.dto.CardExportSubmitDto;
import com.cap.bts.crmdp.dealer.card.service.ICardExportService;
import com.cap.bts.crmdp.dealer.card.util.CSVUtils;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.purchase.dao.IMemberPackageDao;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.framework.codemapping.dao.ICodeMappingDao;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.exception.AppException;
import com.jcraft.jsch.ChannelSftp;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class CardExportServiceImpl implements ICardExportService {

    @Autowired
    private ICardExportDao cardExportDao;

    @Autowired
    private IMemberPackageDao memberPackageDao;
    @Autowired
    private ICodeMappingDao codeMappingDao;
    @Autowired
    private ICodeMapping codeMappingService;
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 24, 2015
     * @see com.cap.bts.crmdp.dealer.card.service.ICardExportService#getExportCardListByQueryDto(com.cap.bts.crmdp.dealer.card.dto.CardExportQueryDto)
     **/
    @Override
    public List<CardGeneration> getExportCardListByQueryDto(CardExportDto dto)
        throws AppException {
        return cardExportDao.getExportCardListByQueryDto(dto);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 27, 2015
     * @see com.cap.bts.crmdp.dealer.card.service.ICardExportService#generateCSVfile(com.cap.bts.crmdp.dealer.card.dto.CardExportQueryDto)
     **/
    @Override
    public List<File> generateCSVfile(List<CardExportSubmitDto> list) throws AppException {
        List<File> files=new ArrayList<File>();
        // 删除未check的导出条目
        for (int i = list.size() - 1; i >= 0; i--) {
            if (!list.get(i).getIsExport()) {
                list.remove(i);
            }
        }
        //循环列表并逐个生成CSV文件
        for(CardExportSubmitDto dto:list){
            //a查询数据库卡表取得当前批次所有卡
            List<MemberPackageInfo> cardList=memberPackageDao.getMemberPackageInfoListByBatchId(dto.getId());
            if(cardList!=null && !cardList.isEmpty()){
                List exportData = new ArrayList<Map>();
                Map map = new LinkedHashMap();
                map.put("1", "卡号");
                map.put("2", "验证码");
                Integer temp=0;
                for(MemberPackageInfo mpi:cardList){
                    //传入卡列表(内容)以及批次信息(文件名称)生成CSV文件
                    Map row= new LinkedHashMap<String, String>();
                    temp++;
                    row.put("1", mpi.getPackageNumber());
                    row.put("2", mpi.getActivationCode());
                    exportData.add(row);
                }
                StringBuilder fileName=new StringBuilder();
                fileName.append(cardList.get(0).getCardGeneration().getCardDefinition().getName())
                .append("_")
                .append(cardList.get(0).getCardGeneration().getCardNumFrom())
                .append("_")
                .append(cardList.get(0).getCardGeneration().getCardNumTo());
                CSVUtils.createCSVFile(exportData, map, "./", fileName.toString()
                 ); 
                files.add(new File("./"+fileName.toString()+".csv"));
            }
        }
        return files;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月2日
     * @see com.cap.bts.crmdp.dealer.card.service.ICardExportService#generateCSVfile()
    **/
    @Override
    public File generateCSVfile(StringBuilder fileName, String outPutPath,List<String> list) throws AppException {
        try {
            File csvFile =new File(outPutPath + fileName);
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8");
            BufferedWriter csvFileOutputStream = new BufferedWriter(osw);
            if(list != null && !list.isEmpty()){
                    csvFileOutputStream.write("#" + (list.size()-1) +"\n");    
                    for (int i = 0; i < list.size(); i++) {
                            csvFileOutputStream.write(list.get(i)+"\n");
                    }
            }
            csvFileOutputStream.flush();
            csvFileOutputStream.close();
            return  csvFile;
        } catch (UnsupportedEncodingException e) {
            throw new AppException("createCSVFile",e);
        } catch (FileNotFoundException e) {
            throw new AppException("createCSVFile",e);
        } catch (IOException e) {
        	throw new AppException("createCSVFile",e);
        }
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月2日
     * @see com.cap.bts.crmdp.dealer.card.service.ICardExportService#getSyncDataViewFromCodeValueByCodeType(java.lang.String)
    **/
    @Override
    public List<CodeInfo> getSyncDataViewFromCodeValueByCodeType(String type) throws AppException {
        return codeMappingDao.getCodeInfoByCodeType(type);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年12月3日
     * @see com.cap.bts.crmdp.dealer.card.service.ICardExportService#getWechatCardListFromView(java.lang.String)
    **/
    @Override
    public List<String> getWechatCardListFromView(String viewName) throws AppException {
        return cardExportDao.getWechatCardListFromView(viewName);
    }


	@Override
	public File processCSVfile(StringBuilder fileName, String outPutPath, List<String> list) throws AppException {
		try {
            File csvFile =new File(outPutPath + fileName);
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(csvFile), "GBK");
            BufferedWriter csvFileOutputStream = new BufferedWriter(osw);
            if(list != null && !list.isEmpty()){
                    for (int i = 0; i < list.size(); i++) {
                            if(i == (list.size()-1)){
                            	csvFileOutputStream.write(list.get(i));
                            }else{
                            	csvFileOutputStream.write(list.get(i)+"\r\n");
                            }
                    }
            }
            csvFileOutputStream.flush();
            csvFileOutputStream.close();
            return  csvFile;
        } catch (UnsupportedEncodingException e) {
            throw new AppException("createCSVFile",e);
        } catch (FileNotFoundException e) {
            throw new AppException("createCSVFile",e);
        } catch (IOException e) {
        	throw new AppException("createCSVFile",e);
        }
	}
	
}
